<?php

/*
 * memcached缓存类
 * @author sufei <87753586@qq.com>
 * @date 2012-07-02
 */

class Cache_Memcached {
	
	//默认过期时间，单位秒
	private $expires = 60;
	
	//配置项
	private $config = array(
		array(
			'host' => '127.0.0.1',
			'port' => 11211,
			'weight' => 1
		)
	);
	
	//memcache对象
	private $_memcached = NULL;
	
	public function __construct($config = array())
	{
		if ( ! $config)
		{
			$this->config = $config;
		}
		
		$this->_memcached = new Memcached();
		foreach ($this->config as $config)
		{
			$this->_memcached->addServer($config['host'], $config['port'], $config['weight']);
		}
	}
	
	/*
	 * 保存
	 * @access public
	 * @param $id string 键名
	 * @param $data mixed 键值数据
	 * @param $expires integer 声明周期
	 * @return boolean
	 */
	public function set($id, $data, $expires = NULL)
	{
		$expires = $expires != FALSE ? intval($expires) : $this->expires;
		return $this->_memcached->set($id, array($data, time(), $expires), $expires);
	}

	/*
	 * 返回缓存数据
	 * @access public
	 * @param $id string 键名
	 * @return mixed
	 */
	public function get($id)
	{
		$data = $this->_memcached->get($id);
		return (is_array($data)) ? $data[0] : FALSE;
	}
	
	/*
	 * 返回缓存详细信息
	 * @access public
	 * @param $id string 键名
	 * @return array|boolean
	 */
	public function detail($id)
	{
		$result = $this->_memcached->get($id);
		if ( ! is_array($result) && count($result) != 3)
		{
			return FALSE;
		}
		list($data, $time, $expires) = $result;
		/*
		 * data => 缓存数据
		 * time => 保存时候的时间，秒
		 * expires => 缓存时间，秒
		 */
		return array(
			'data' => $data,
			'time' => $time,
			'expires' => $expires
		);
	}
	
	/*
	 * 删除
	 * @access public
	 * @param $id string 键名
	 * @return boolean
	 */
	public function delete($id)
	{
		return $this->_memcached->delete($id);
	}
	
	/*
	 * 清空
	 * @access public
	 * @return boolean
	 */
	public function clean()
	{
		return $this->_memcached->flush();
	}
	
}